package com.gjy.sentinel.core.sentinel;

import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.gjy.sentinel.core.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 示例：把内存中的规则写回到本地 JSON 文件（模拟 Dashboard “推送”）。
 * 实际生产一般是写入 Nacos、Zookeeper、Apollo 等。
 *
 * @author gjy
 * @version 1.0
 * @since 2025-10-14 17:15:29
 */
public class RulePublisher {
    private static final Logger log = LoggerFactory.getLogger(RulePublisher.class);

    private static final String RULE_DIR = "sentinel-rules";

    public static void publishFlow(List<FlowRule> rules) throws IOException {
        write(RULE_DIR + "/flow.json", rules);
    }

    public static void publishDegrade(List<DegradeRule> rules) throws IOException {
        write(RULE_DIR + "/degrade.json", rules);
    }

    public static void publishSystem(List<SystemRule> rules) throws IOException {
        write(RULE_DIR + "/system.json", rules);
    }

    public static void publishParam(List<ParamFlowRule> rules) throws IOException {
        write(RULE_DIR + "/param.json", rules);
    }

    public static void publishAuthority(List<AuthorityRule> rules) throws IOException {
        write(RULE_DIR + "/authority.json", rules);
    }

    private static void write(String filePath, Object obj) throws IOException {
        File f = new File(filePath);
        if (!f.getParentFile().exists()) {
            boolean mkdir = f.getParentFile().mkdirs();
            log.info("创建目录: {}, {}", f.getParentFile().getAbsoluteFile(), mkdir);
        }
        JsonUtil.writeJson(f, obj);
    }

}
